import { Component, OnInit,ViewEncapsulation } from '@angular/core';
import { PathParam } from '../../../config/pathParam'
import {DialogService} from 'primeng/dynamicdialog';
import { TutorialService } from 'src/app/service/tutorialService';
import { ActivatedRoute } from '@angular/router';
import { MarkdownFile } from '../../../model/MarkdownFile'
import { DatePipe } from '@angular/common';
import {MessageService} from 'primeng/api';
import { CookieService } from 'ngx-cookie-service';

@Component({
  selector: 'app-notebook',
  templateUrl: './notebook.component.html',
  styleUrls: ['./notebook.component.css'],
  providers: [DialogService],
  encapsulation:ViewEncapsulation.None
})
export class NotebookComponent implements OnInit {

  //md file info
  fileId:number;
  filename:string;
  text:string = "";
  author:string;

  upload_display = false;
  catalogs:any[];
  selectedCatalogs:any[];


  startPos:any = 0;
  endPos:any = 0;
  display:boolean = false;

  tutorialWin_display = false;
  helpWin_display = false;

  constructor(public dialogService:DialogService,
              private tutorialService: TutorialService,
              private route: ActivatedRoute,
              private datePipe: DatePipe,
              private messageService: MessageService,
              private cookieService: CookieService) { }

  ngAfterViewInit(){
    document.getElementById("inputarea").setAttribute("style", "height:"+(window.innerHeight - 100).toString()+"px;");
  }
  ngOnInit(): void {
    this.author = this.cookieService.get("username");
    this.catalogs = [
      {label:'推荐', value:'recommand'},
      {label:'控制算法', value:'controllMethod'},
      {label:'机械设计', value:'mechineDesign'}
    ]
    this.fileId =  this.route.snapshot.queryParams["id"];
      this.tutorialService.getMarkdownFile(this.fileId).subscribe(result=>{
        console.log(result);
        this.filename = result.filename;
        this.text = result.text==null ? "":result.text;
        this.selectedCatalogs = result.catalog.split(";");
      });

    document.getElementById("inputarea").focus();
  }

  uploadpic(event){
    if(event.originalEvent.body.status == "ok"){
      let picname = event.originalEvent.body.filename;
      let pictext = "!["+event.files[0].name+"]("+PathParam.picture_url+picname+")";
      this.insertText(pictext);
    }
    else {
      alert("上传图片失败，图片大小不得超过2M");
    }
  }
  uperrorpic(event){
    alert("上传图片失败");
  }
  uploaddoc(event){
    if(event.originalEvent.body.status == "ok"){
      let docname = event.originalEvent.body.filename;
      let doctext = "["+event.files[0].name+"]("+PathParam.document_url+docname+")";
      this.insertText(doctext);
    }
    else {
      alert("上传文档失败，文档大小不得超过10M");
    }
  }
  uperrordoc(event){
    alert("上传文档失败");
  }

  getCursorPos(textarea){
    this.startPos = textarea.selectionStart;
    this.endPos = textarea.selectionEnd;
  }

  insertText(text) {
    if (this.startPos === undefined || this.endPos === undefined) return
    this.text = this.text.substring(0, this.startPos) + text + this.text.substring(this.endPos)
    document.getElementById("inputarea").focus();
    /*set cursor position
    if(textarea.setSelectionRange){
      textarea.focus();
      textarea.setSelectionRange(3,3);
    }
    else if(textarea.createTextRange){
      var range = textarea.createTextRange();
      range.collapse(true);
      range.moveEnd('character',3);
      range.moveStart('character',3);
      range.select();
    }*/
  }

  uploadtext(){
    // const ref = this.dialogService.open(UploadComponent, {
    //     data:{
    //       text:this.text,
    //       filename: this.filename,
    //     },
    //     header: '上传文件',
    //     width: '650px',
    //     height: '420px',
    // });
    let markdownfile = new MarkdownFile();
    markdownfile.id = this.fileId;
    markdownfile.author = this.author;
    markdownfile.date = this.datePipe.transform(new Date(),'yyyy-MM-dd hh:mm:ss');
    markdownfile.catalog = this.selectedCatalogs.join(";");
    markdownfile.filename = this.filename;
    markdownfile.text = this.text;
    console.log(markdownfile);
    this.tutorialService.updateMarkdownFile(markdownfile).subscribe(result=>{
      this.messageService.add({severity:'success', summary: '保存成功', detail:'文件已保存'});
      this.upload_display = false;
    },
    error=>{
      this.messageService.add({severity:'error', summary: '保存失败', detail:error});

    });
  }


  showTutorialWin(){
    this.tutorialWin_display = true;

  }
  showHelpWin(){
    this.helpWin_display = true;
  }
  showUpload(){
    this.upload_display = true;
  }

  onResize(){
    document.getElementById("inputarea").setAttribute("style", "height:"+(window.innerHeight - 100).toString()+"px;");
  }

}
